<template>
  <div>
    <el-select v-model="selectedName"
               :multiple="multiple"
               placeholder="请选择"
               :filterable="filterable"
               clearable
               :popper-append-to-body="true"
                @remove-tag='removeTag'
                @clear="clear"
                :disabled="disabled"
                :filter-method="assetsTypeFilter"
                ref="select-tree"
                @change="changeFun"
                style="width: 100%">

    <el-option :value="selectTree" class="setstyle" disabled>
      <el-tree
          :data="data"
          :props="props"
          ref="tree"
          node-key="id"
          :check-strictly="!checkChildren"
          :show-checkbox="multiple"
          :default-expand-all="expandAll"
          :expand-on-click-node="false"
          check-on-click-node
          @check-change="checkChangeClick"
          :filter-node-method="filterNode"/>
    </el-option>

    </el-select>
  </div>

</template>

<script>
export default {
  name: 'select-tree',
  components: {},
  props: {
    //v-model值
    value: {
      type: [String, Number],
      default: ''
    },
    //树结构数据
    data: {
      type: Array,
      default: () => [],
    },
    filterable: {
      type: Boolean,
      default: false
    },

    disabled: {
      type: Boolean,
      default: false
    },
    //值是数组还是逗号隔开字符串
    valueArray: {
      type: Boolean,
      default: false
    },
    expandAll:{
      type: Boolean,
      default: false
    },
    checkChildren:{
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },

    // 每个树节点用来作为唯一标识的属性
    nodeKey: {
      type: [String, Number],
      default: 'id'
    },

    //tree的props配置
    props: {
      type: Object,
      default: function () {
        return {
          label: 'label',
          children: 'children'
        }
      }
    },

  },



  data() {
    return {
      selectedName: [],
      selectedId: [],
      selectTree: [],
    }
  },

  watch: {
    value: {
      handler(val) {
        this.init(val)
      },
      immediate: true
    },
    data:{
      handler(data) {
        console.log(data)
        this.init(this.value)
      },
    }
  },

  mounted() {
    this.selectTree = this.flatten(this.data)
  },


  methods: {

    flatten(arr) {
      return [].concat(
          ...arr.map((item) => {
            if (item.children) {
              let arr = [].concat(item, ...this.flatten(item.children))
              delete item.children
              return arr
            }
            return [].concat(item)
          }),
      )
    },

    changeFun(){
      this.$emit('change')
    },

    assetsTypeFilter(val) {
      this.$refs.tree.filter(val)
    },


    init(val) {
      this.selectedName = [];
      this.selectedId = [];
      if(val){
        let arr = val
        if (!Array.isArray(val)){
          arr = val.toString().split(',')
        }
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr)
          const nodes = this.$refs.tree.getCheckedNodes()
          this.selectedName = nodes.map((item) => item[this.props.label])
          this.selectedId = nodes.map((item) => item[this.nodeKey])
        })
      }else{
        this.$refs.tree.setCheckedKeys(null)
      }
    },


    checkChangeClick(data, self, child) {
      console.log(child)
      //多选
      if (this.multiple) {
        let datalist = this.$refs.tree.getCheckedNodes()
        this.selectedName = []
        this.selectedId = [];
        datalist.forEach((item) => {
          this.selectedName.push(item[this.props.label])
          this.selectedId.push(item[this.nodeKey])
        })
        //将值传递到父组件中的v-model
        let val = this.valueArray?this.selectedId:this.selectedId.join(',')
        this.$emit('input', val)
        this.$emit('change')
      }
      //单选
      else {
        if (self) {
          this.$refs.tree.setCheckedNodes([data])
          this.multiple = false
          this.selectedName = [data[this.props.label]]
          this.selectedId = [data[this.nodeKey]]
          //将值传递到父组件中的v-model
          let val = this.valueArray?this.selectedId:this.selectedId.join(',')
          this.$emit('input', val)
          this.$emit('change')
          this.$refs['select-tree'].blur();
        }
      }
    },


    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    clear(){
      this.selectedName = []
      this.selectedId = []
      let val = this.valueArray?this.selectedId:this.selectedId.join(',')
      this.$emit('input', val)
    },


    removeTag(tag) {
      let checNodes = this.$refs.tree.getCheckedNodes();
      for (let i = 0; i < checNodes.length; i++) {
        if (checNodes[i][this.props.label] === tag) {
          checNodes.splice(i, 1);
          break;
        }
      }
      this.$refs.tree.setCheckedNodes(checNodes);
    }

  },




}
</script>
<style lang="scss">
.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}
</style>
<style lang="scss" scoped></style>
